package com.riatimes.net.http
{
	import com.adobe.serialization.json.JSON;
	import com.riatimes.mvc.model.vo.DataParamVO;
	import com.riatimes.mvc.model.vo.DataTypeVO;
	import com.riatimes.util.Logger;
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLVariables;
	import flash.system.System;
	
	import org.puremvc.as3.patterns.facade.Facade;

	public class HttpLoader
	{
		private var loader:URLLoader;
		private var facade:Facade;
		private var vo:DataParamVO;
		public function HttpLoader(facade:Facade,vo:DataParamVO)
		{
			this.facade=facade;
			this.vo=vo;
			getData(vo);
		}
		
		private function getData(vo:DataParamVO):void {
			
			loader = new URLLoader();
			
			var request:URLRequest = new URLRequest(vo.url);
			var variable:URLVariables= new URLVariables();
			if (vo.params!=null) {				
				for (var item:* in vo.params) {
					variable[item] = vo.params[item];
				}
			}
			//variable["lang"] = ModelLocator.LANGUAGE;
			variable["r"] = new Date().getTime();
			request.data = variable;			
			request.method = vo.method;
			loader.load(request);
			loader.addEventListener(Event.COMPLETE, __completeHandle);
			loader.addEventListener(IOErrorEvent.IO_ERROR, __ioErrorEventHandle);			
			
			Logger.logInfo("request url:  " + vo.url);			
			var ts:String = "";
			for (var p:* in vo.params) {
				ts += p+":"+vo.params[p]+" ";
			}
			Logger.logInfo("params:  " +ts);
		}
		
		private function __ioErrorEventHandle(e:IOErrorEvent):void {
			Logger.logError("error url:"+vo.url);
		}
		
		private function __completeHandle(e:Event):void {
			var jsonObj:Object;
			var xmlList:XMLList;
			var item:Object;
			if (vo.dataType == DataTypeVO.HTTP_JOSN)
			{
				Logger.logInfo(loader.data);
				try {
					jsonObj = JSON.decode(e.currentTarget.data);
					facade.sendNotification(vo.callbackEvent, jsonObj.data);
					
					
				}catch (e:Error) {
					Logger.logError("json 格式错误！");
					return;
				}				
				if (jsonObj.status!= 200)
				{
					Logger.logWarning(jsonObj.msg);					
				}
			}else if (vo.dataType==DataTypeVO.HTTP_XML)
			{
				xmlList = XMLList(e.currentTarget.data);
				
				if (xmlList.@c != 200)
				{
					return
				}						
			}else if (vo.dataType == DataTypeVO.HTTP_TXT)
			{
				var urlVars:URLVariables = new URLVariables(e.currentTarget.data);
				if (urlVars.c != 200)
				{
					return;
				}
			}

			loader.removeEventListener(Event.COMPLETE, __completeHandle);
			loader.removeEventListener(IOErrorEvent.IO_ERROR, __ioErrorEventHandle);	
			loader=null;
		}	
	}
}